<template>
  <div
    v-loading="loading"
    class="monthPlanAdd"
  >
    <div class="pub-detail-title-btn">
      <excel
        ref="exportSelect"
        file-name="物资明细"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportSelect"
        >
          导出选中
        </a-button>
      </excel>
      <excel
        ref="exportAll"
        file-name="物资明细"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportAll"
        >
          导出全部
        </a-button>
      </excel>
    </div>
    <a-table
      ref="table"
      :pagination="false"
      :columns="columns"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['number', 'settleAmount', 'sumSettle','controlAmount','sumTotal',
                       'sumSettleControlDiff','sumSettleControl','sumUnitPoint','remark']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="record.editable">
            <BaseInput
              style="margin: -5px 0"
              :value="text"
              :disabled="col === 'sumSettle' || col === 'sumTotal' || col === 'sumSettleControlDiff'
                || col === 'sumSettleControl' || col === 'sumUnitPoint'"
              @change="e => handleChange(e.target.value, record.id, col)"
            />
          </template>
          <template v-else>
            {{ col === 'analysisIdentify' ? record.analysisIdentifyStr : text }}
          </template>
        </div>
      </template>
      <template
        slot="operation"
        slot-scope="text, record, index"
      >
        <div class="editable-row-operations">
          <span v-if="record.editable && state !== 3">
            <a @click="() => save(record.id)">保存</a>
            <a @click="() => cancel(record.id)">取消</a>
          </span>
          <span v-else>
            <a
              :disabled="editingKey !== ''"
              @click="() => edit(record.id)"
            >编辑</a>
          </span>
        </div>
      </template>
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
    <!--        <b-table-->
    <!--            :exportConfig=" {use: true,select: '物资明细选中',  all: '物资明细全部'}"-->
    <!--            :columns="columns"-->
    <!--            bordered-->
    <!--            :scroll="{ x: 1300 }"-->
    <!--            :request="loadData"-->
    <!--        >-->

    <!--        </b-table>-->
    <!-- <material-list ref="detailDialog" @createList="createList"></material-list> -->
  </div>
</template>
<script>
import { selectOption } from '@/api/material/goods/goods'
import { materialsList } from '@/api/material/procurement/apply'
import { reviewMaterialsEdit } from '@/api/material/procurement/review'
import { columns } from './insideModel'

const data = []
export default {
	name:'a'+Date.now(),
    name: 'RebarPlan',
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        },
        applyId: {
            type: String
        }
    },
    data() {
        this.cacheData = data.map(item => ({ ...item }))
        return {
            loading: false,
            selectedRows: [],
            pageNo: 1,
            pageSize: 10,
            queryParam: {},
            totalSize: 0,
            selectedRowKeys: [],
            columns: columns,
            editingKey: '',
            data: this.tableData,
            optionArr: [],
            selectedId: [],
            rules: {
                number: [
                    { rule: 'required', message: '数量不能为空' },
                    { rule: 'number', message: '数量必须为数字' }
                ],
                settleAmount: [
                    { rule: 'required', message: '发包人结算单价不能为空' },
                    { rule: 'decimal', message: '发包人结算单价必须为数字' }
                ],
                controlAmount: [
                    { rule: 'required', message: '招标控制单价不能为空' },
                    { rule: 'decimal', message: '招标控制单价必须为数字' }
                ]
            },

            loadData: params => {
                return materialsList(Object.assign(params, { purchaseApplyId: this.applyId }))
            }
        }
    },
    watch: {},
    mounted: function() {
        this.getOption()
        if (this.state === 3) {
            this.editingKey = true
        }
        this.list()
        this.initErrMessage(this.rules)
        // this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
        // this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    },
    methods: {
        // createList:function(selectRow){
        //     let _this = this;
        //     let params = {
        //         materialName:selectRow.name,
        //         materialCode:selectRow.code,
        //         materialModel:selectRow.specificationModel,
        //         unit:selectRow.unitId,
        //         purchaseApplyId:_this.id,
        //         number:'',
        //         taxPrice:'',
        //         totalPrice:'',
        //         materialId:selectRow.id
        //     };
        //     materialsAdd(params).then(res => {
        //         if (res.code === 200) {
        //             _this.list();
        //         }
        //     })
        // },
        exportSelect: function() {
            if (this.selectedRowKeys.length > 0) {
                this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
            } else {
                this.$message.warning('请选择需要导出的数据')
            }
        },
        exportAll: function() {
            // 参数：查询条件、导出的回调
            if (this.totalSize) {
                this.pageNo = 1
                this.list(this.$refs.exportAll.setDataAndGenerate)
            } else {
                this.$message.warning('没有可导出的数据')
            }
        },
        getOption: function() {
            let _this = this
            selectOption({
                type: 0
            }).then(res => {
                if (res.code === 200) {
                    _this.optionArr = res.data
                }
            })
        },
        openDailog: function() {
            if (this.editingKey !== '') {
                this.$message.error('新增前请结束当前操作行')
                return
            }
            this.$refs.detailDialog.open()
        },
        // 删除
        handleDel() {
            this.delList(planDetailListDel, () => {
                this.initTable()
                this.selectedId = []
                this.selectedRowKeys = []
                this.selectedRows = []
                this.editingKey = ''
            }, { ids: this.selectedId })
        },
        initTable() {
            this.pageNo = 1
            this.list()
        },
        list(callback) {
            this.loading = true
            let _this = this
            materialsList({
                pageSize: callback ? _this.totalSize : _this.pageSize,
                pageNo: _this.pageNo,
                purchaseApplyId: _this.applyId
            }).then(res => {
                if (res.code === 200) {
                    if (callback) {
                        if (res.data.length) {
                            callback(res.data)
                        } else {
                            this.$message.warning('没有可导出的数据')
                        }
                        this.loading = false
                        return
                    }
                    _this.data = res.data
                    _this.totalSize = res.totalSize
                    _this.cacheData = res.data.map(item => ({ ...item }))
                }
                this.loading = false
            })
        },
        handleChange(value, key, column) {
            const newData = [...this.data]
            const target = newData.filter(item => key === item.id)[0]
            let sumSettleDiff = '',
                sumSettle = '',
                sumTotal = '',
                sumTotalDiff = '',
                sumUnitDiff = '',
                sumUnit = ''
            if (target) {
                target[column] = value
                target['sumSettle'] = target['number'] * target['settleAmount']
                target['sumTotal'] = target['number'] * target['controlAmount']
                target['sumSettleControlDiff'] = target['settleAmount'] - target['controlAmount']
                target['sumSettleControl'] = target['sumSettle'] - target['sumTotal']
                // target['sumUnitPoint'] = target['number'] * target['settleAmount'];
                newData.map(function(item) {
                    sumSettleDiff += item.sumSettleDiff
                    sumSettle += item.sumSettle
                    sumTotal += item.sumTotal
                    sumTotalDiff += item.sumTotalDiff
                    sumUnitDiff += item.sumUnitDiff
                    sumUnit += item.sumUnit
                })
                if (this.rules[column]) {
                    this.customValidation(value, column)
                }
                this.data = newData
                this.$emit('getTotal', {
                    sumSettleDiff: sumSettleDiff, sumSettle: sumSettle, sumTotal: sumTotal,
                    sumTotalDiff: sumTotalDiff, sumUnitDiff: sumUnitDiff, sumUnit: sumUnit
                })
            }
        },
        edit(key) {
            const newData = [...this.data]
            const target = newData.filter(item => key === item.id)[0]
            this.editingKey = key
            if (target) {
                target.editable = true
                this.data = newData
                console.log(target.editable)
            }
        },
        handlePageChange(pageNo, pageSize) {
            this.pageNo = pageNo
            this.getTable()
        },
        showSizeChange(pageNo, pageSize) {
            this.pageSize = pageSize
            this.initTable()
        },
        save(key) {
            // 编辑保存
            const newData = [...this.data]
            const newCacheData = [...this.cacheData]
            const target = newData.filter(item => key === item.id)[0]
            for (let key in target) {
                if (this.rules[key]) {
                    this.customValidation(target[key], key)
                }
            }
            for (let i in this.customValidationErr) {
                if (i) {
                    return
                }
            }
            this.loading = true
            reviewMaterialsEdit(target).then(res => {
                if (res.code === 200) {
                    this.$message.success('编辑成功')
                    this.initTable()
                }
                this.loading = false
            })
            const targetCache = newCacheData.filter(item => key === item.id)[0]
            if (target && targetCache) {
                delete target.editable
                this.data = newData
                Object.assign(targetCache, target)
                this.cacheData = newCacheData
            }
            this.editingKey = ''
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedId = []
            selectedRows.map(i => {
                this.selectedId.push(i.id)
            })
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },
        cancel(key) {
            const newData = [...this.data]
            const target = newData.filter(item => key === item.id)[0]
            this.editingKey = ''
            this.planDate = null
            this.selectVal = null
            if (target) {
                Object.assign(target, this.cacheData.filter(item => key === item.id)[0])
                // target.editable = false;
                delete target.editable
                this.data = newData
            }
        }
    }
}
</script>
